package com.hh.admin.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.hh.admin.entity.SysGroupUser;
import com.hh.admin.entity.SysUser;
import com.hh.admin.entity.SysUserRole;
import com.hh.admin.mapper.SysGroupUserMapper;
import com.hh.admin.mapper.SysUserMapper;
import com.hh.admin.mapper.SysUserRoleMapper;
import com.hh.admin.service.ISysUserService;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hxn
 * @since 2018-01-16
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

	@Autowired
	SysUserMapper sysUserMapper;
	
	@Autowired
	SysGroupUserMapper sysGroupUserMapper;
	
	@Autowired
	SysUserRoleMapper sysUserRoleMapper;
	
	@Override
	public SysUser getByAccount(String account) {
		return sysUserMapper.getByAccount(account);
	}

	@Override
	@Transactional
	public boolean addUser(SysUser user, Long groupId, Long[] roleId) {
		sysUserMapper.insert(user);
		SysGroupUser groupUser = new SysGroupUser();
		groupUser.setGroupId(groupId);
		groupUser.setUserId(user.getId());
		sysGroupUserMapper.insert(groupUser);
		SysUserRole userRole = new SysUserRole();
		for(Long rid : roleId){
			userRole.setRoleId(rid);
			userRole.setUserId(user.getId());
			sysUserRoleMapper.insert(userRole);
		}
		return true;
	}

	@Override
	public SysUser getById(Long id) {
		SysUser user = sysUserMapper.getById(id);
		return user;
	}

	@Override
	@Transactional
	public boolean updateById(SysUser user, Long groupId, Long[] roleId) {
		sysUserMapper.updateById(user);
		Map<String, Object> columnMap = new HashMap<String, Object>();
		columnMap.put("USER_ID", user.getId());
		sysGroupUserMapper.deleteByMap(columnMap);
		sysUserRoleMapper.deleteByMap(columnMap);
		SysGroupUser groupUser = new SysGroupUser();
		groupUser.setGroupId(groupId);
		groupUser.setUserId(user.getId());
		sysGroupUserMapper.insert(groupUser);
		SysUserRole userRole = new SysUserRole();
		for(Long rid : roleId){
			userRole.setRoleId(rid);
			userRole.setUserId(user.getId());
			sysUserRoleMapper.insert(userRole);
		}
		return true;
	}

	@Override
	public boolean deleteById(Long id) {
		sysUserMapper.deleteById(id);
		Map<String, Object> columnMap = new HashMap<String, Object>();
		columnMap.put("USER_ID", id);
		sysGroupUserMapper.deleteByMap(columnMap);
		sysUserRoleMapper.deleteByMap(columnMap);
		return false;
	}
	
}
